import axios from 'axios'
import { IOption } from '../types/base'

class PendingRequest {
	// 等待队列Map对象
	private pendingMap = new Map()

	/**
	 * 生产唯一key 用于存储axios取消请求对象
	 *
	 * @param {config}
	 * @returns 返回配置项生成唯一的key
	 * @memberof PendingRequest
	 */
	getPendingKey(config: IOption) {
		const { url, method, params } = config
		return [url, method, JSON.stringify(params)].join('&')
	}

	/**
	 * 添加axios取消请求对象
	 *
	 * @param {config}
	 * @memberof PendingRequest
	 */
	addPending(config: IOption) {
		const pendingKey = this.getPendingKey(config)
		config.cancelToken =
			config.cancelToken ||
			new axios.CancelToken((cancel) => {
				if (!this.pendingMap.has(pendingKey)) {
					this.pendingMap.set(pendingKey, cancel)
				}
			})
	}

	/**
	 * 执行取消请求方法并移除取消请求对象
	 *
	 * @param {config}
	 * @memberof PendingRequest
	 */
	removePending(config: IOption) {
		const pendingKey = this.getPendingKey(config)
		if (this.pendingMap.has(pendingKey)) {
			const cancelToken = this.pendingMap.get(pendingKey)
			cancelToken('取消了请求')
			this.pendingMap.delete(pendingKey)
		}
	}
}

export default new PendingRequest()
